<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-select
          @visible-change="visibleChangeStreet"
          @change="changeStreet"
          v-model="query.streetId"
          placeholder="请选择街道"
          class="handle-select mr10"
          clearable
        >
          <el-option
            v-for="(item, index) in streetList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <el-select
          @visible-change="visibleChangeCommunity"
          @change="changeCommunity"
          v-model="query.communityId"
          placeholder="请选择社区"
          class="handle-select mr10"
        >
          <el-option
            v-for="(item, index) in communityList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>

        <el-select
          @visible-change="visibleChangeVillage"
          @change="changeVillage"
          v-model="query.villageId"
          placeholder="请选择小区"
          class="handle-select mr10"
        >
          <el-option
            v-for="(item, index) in villageList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>

        <div style="color: #333; font-size: 16px; margin-top: 48px;">
          小区数据
        </div>

        <hr
          style="background-color: #ccc;border:none; height:1px; margin: 18px 0;"
        />
        <div
          style="
            display: grid;
            grid-auto-flow: row;
            justify-content: space-between; 
            grid-template-rows: 50px 32px;
            grid-template-columns:200px 200px 200px; 
          "
        >
          <div style="text-align:left;">
            实际户数:
            <el-input
              v-model="form.actualNum"
              style="width: 120px"
              placeholder="实际户数"
              clearable
            ></el-input>
          </div>
          <div style="text-align:center;">
            入住户数:
            <el-input
              v-model="form.checkInNum"
              style="width: 120px;"
              placeholder="入住户数"
              clearable
            ></el-input>
          </div>
          <div style="text-align:right;">
            参与户数:
            <el-input
              v-model="form.partakeNum"
              style="width: 120px"
              placeholder="参与户数"
              clearable
            ></el-input>
          </div>

          <div style="text-align:center;">
            知晓率:
            <el-input
              v-model="form.awarenessRate"
              style="width: 120px"
              placeholder="知晓率"
              clearable
            ></el-input>
          </div>
          <div style="text-align:right">
            正确率:
            <el-input
              v-model="form.accuracy"
              style="width: 120px"
              placeholder="正确率"
              clearable
            ></el-input>
          </div>
        </div>

        <div style="color: #333; font-size: 16px; margin-top: 48px;">
          垃圾重量
        </div>
        <hr
          style="background-color: #ccc;border:none; height:1px; margin: 18px 0;"
        />

        <div
          style="
            display: grid;
            grid-auto-flow: row;
            justify-content: space-between; 
            grid-template-rows: 50px 32px;
            grid-template-columns:200px 200px 200px; 
          "
        >
          <div style="text-align: left;">
            易腐垃圾:
            <el-input
              v-model="form.perishable"
              style="width: 120px"
              placeholder="易腐垃圾"
            ></el-input>
          </div>
          <div style="text-align: center;">
            可回收物:
            <el-input
              v-model="form.recyclable"
              style="width: 120px"
              placeholder="可回收物"
            ></el-input>
          </div>
          <div style="text-align: right;">
            有害垃圾:
            <el-input
              v-model="form.harmful"
              style="width: 120px"
              placeholder="有害垃圾"
            ></el-input>
          </div>

          <div style="text-align: left;">
            其他垃圾:
            <el-input
              v-model="form.other"
              style="width: 120px"
              placeholder="其他垃圾"
            ></el-input>
          </div>
        </div>

        <div style="color: #333; font-size: 16px; margin-top: 48px;">
          可回收分类明细（百分比输入，相加必须等100%）
        </div>
        <hr
          style="background-color: #ccc;border:none; height:1px; margin: 18px 0;"
        />

        <div
          style="
            display: grid;
            grid-auto-flow: row;
            justify-content: space-between; 
            grid-template-rows: 50px 32px;
            grid-template-columns:200px 200px 200px; 
          "
        >
          <div style="text-align: left;">
            塑料:
            <el-input
              v-model="form.plastic"
              style="width: 120px"
              placeholder="塑料"
            ></el-input>
          </div>
          <div style="text-align: center">
            玻璃:
            <el-input
              v-model="form.glass"
              style="width: 120px"
              placeholder="玻璃"
            ></el-input>
          </div>
          <div style="text-align: right;">
            纸类:
            <el-input
              v-model="form.paper"
              style="width: 120px"
              placeholder="纸类"
            ></el-input>
          </div>

          <div style="text-align: left;">
            金属:
            <el-input
              v-model="form.metal"
              style="width: 120px"
              placeholder="金属"
            ></el-input>
          </div>
          <div style="text-align: center;">
            纺织:
            <el-input
              v-model="form.spin"
              style="width: 120px"
              placeholder="纺织"
            ></el-input>
          </div>
        </div>

        <div style="color: #333; font-size: 16px; margin-top: 48px;">
          参与率趋势
        </div>
        <hr
          style="background-color: #ccc;border:none; height:1px; margin: 18px 0;"
        />
        <div id="wrapper-progress">
          <div id="box" v-for="(n, i) in 6" :key="i">
            <div id="progress">
              <div id="progress_head"></div>
              <span id="span"></span>
            </div>
            <div id="percentage">{{ form.participationRate[i] }}</div>
          </div>
        </div>

        <div style="color: #333; font-size: 16px; margin-top: 48px;">
          垃圾收运量趋势图
        </div>
        <hr
          style="background-color: #ccc;border:none; height:1px; margin: 18px 0;"
        />

        <h3 style="margin-bottom: 10px;">易腐:</h3>
        <div
          style="
            display: grid;
            grid-auto-flow: row;
            justify-content: space-between; 
            grid-template-rows: 50px 50px 80px;
            grid-template-columns:120px 120px 120px; 
          "
        >
          <el-input
            v-for="(n, i) in 7"
            :key="i"
            v-model="form.perishables[i]"
            style="width: 120px"
            placeholder="易腐"
            max="1200"
            type="number"
          ></el-input>
        </div>
        <h3 style="margin-bottom: 10px;">可回收:</h3>
        <div
          style="
            display: grid;
            grid-auto-flow: row;
            justify-content: space-between; 
            grid-template-rows: 50px 50px 80px;
            grid-template-columns:120px 120px 120px; 
          "
        >
          <el-input
            v-for="(n, i) in 7"
            :key="i"
            v-model="form.recyclables[i]"
            style="width: 120px"
            placeholder="可回收"
            max="1200"
            type="number"
          ></el-input>
        </div>
        <h3 style="margin-bottom: 10px;">有害:</h3>
        <div
          style="
            display: grid;
            grid-auto-flow: row;
            justify-content: space-between; 
            grid-template-rows: 50px 50px 80px;
            grid-template-columns:120px 120px 120px; 
          "
        >
          <el-input
            v-for="(n, i) in 7"
            :key="i"
            v-model="form.harmfuls[i]"
            style="width: 120px"
            placeholder="有害"
            max="1200"
            type="number"
          ></el-input>
        </div>
        <h3 style="margin-bottom: 10px;">其他:</h3>
        <div
          style="
            display: grid;
            grid-auto-flow: row;
            justify-content: space-between; 
            grid-template-rows: 50px 50px 0px;
            grid-template-columns:120px 120px 120px; 
          "
        >
          <el-input
            v-for="(n, i) in 7"
            :key="i"
            v-model="form.others[i]"
            style="width: 120px"
            placeholder="其他"
            max="1200"
            type="number"
          ></el-input>
        </div>
      </div>
      <el-button type="primary" @click="saveAdd">提交</el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "bigscreenadd",
  data() {
    return {
      query: {
        address: "",
        name: "",
        pageIndex: 1,
        pageSize: 20,
        streetId: "",
        streetName: "",
        communityId: "",
        communityName: "",
        villageId: "",
        villageName: ""
      },
      tableData: [],
      streetList: [],
      communityList: [],
      villageList: [],

      multipleSelection: [],
      delList: [],
      editVisible: false,
      pageTotal: 0,
      form: {
        actualNum: "",
        checkInNum: "",
        partakeNum: "",
        // garbageNum: "",
        awarenessRate: "",
        accuracy: "",
        perishable: "",
        recyclable: "",
        harmful: "",
        other: "",
        plastic: "",
        glass: "",
        paper: "",
        metal: "",
        spin: "",
        participationRate: ["0%", "0%", "0%", "0%", "0%", "0%"],
        perishables: [],
        recyclables: [],
        harmfuls: [],
        others: []
      },
      idx: -1,
      id: -1
    };
  },
  watch: {
    "$route.query": function(newVal, oldVal) {
      console.log(newVal, oldVal);

      if (!newVal.id) {
        // 新增
        // this.$route.meta.title = "数据大屏新增";
        console.log(11111);
        this.clearForm();
      } else {
        // 编辑
        // this.$route.meta.title = "数据大屏编辑";
        this.initForm(newVal.id);
      }
    }
  },
  created() {
    // this.getData();
    var id = this.$route.query.id;
    if (!id) {
      // 新增
      // this.$route.meta.title = "数据大屏新增";
      this.clearForm();
    } else {
      // 编辑
      // this.$route.meta.title = "数据大屏编辑";
      this.initForm(id);
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initProgress();
    });
  },
  methods: {
    clearForm() {
      this.form = {
        actualNum: "",
        checkInNum: "",
        partakeNum: "",
        // garbageNum: "",
        awarenessRate: "",
        accuracy: "",
        perishable: "",
        recyclable: "",
        harmful: "",
        other: "",
        plastic: "",
        glass: "",
        paper: "",
        metal: "",
        spin: "",
        participationRate: ["0%", "0%", "0%", "0%", "0%", "0%"],
        perishables: [],
        recyclables: [],
        harmfuls: [],
        others: []
      };
      this.query = {
        address: "",
        name: "",
        pageIndex: 1,
        pageSize: 20,

        streetId: "",
        streetName: "",
        communityId: "",
        communityName: "",
        villageId: "",
        villageName: ""
      };
      this.streetList = [];
      this.communityList = [];
      this.villageList = [];

      this.$nextTick(() => {
        var oProgress_head = document.querySelectorAll("#progress_head");
        var oSpans = document.querySelectorAll("#span");
        oSpans.forEach(item => {
          item.style.left = "0px";
        });
        oProgress_head.forEach(item => {
          item.style.width = "0px";
        });
      });
    },
    initForm(id) {
      this.$axios
        .get(`screen/screendata/${id}`)
        .then(({ data: res }) => {
          console.log(res);
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }

          // 垃圾收运量趋势图
          res.data.collectionTrend = res.data.collectionTrend
            ? JSON.parse(res.data.collectionTrend)
            : null;

          this.form.perishables = res.data.collectionTrend["perishableTrend"];
          this.form.recyclables = res.data.collectionTrend["recyclableTrend"];
          this.form.harmfuls = res.data.collectionTrend["harmfulTrend"];
          this.form.others = res.data.collectionTrend["otherTrend"];

          // 可回收分类明细
          res.data.recycleSort = res.data.recycleSort
            ? JSON.parse(res.data.recycleSort)
            : null;
          this.form.plastic = res.data.recycleSort.plastic;
          this.form.glass = res.data.recycleSort.glass;
          this.form.paper = res.data.recycleSort.paper;
          this.form.metal = res.data.recycleSort.metal;
          this.form.spin = res.data.recycleSort.textile;

          //  街道、社区、小区
          this.query.streetId = res.data.districtId;
          this.query.communityId = res.data.communityId;
          this.query.villageId = res.data.villageId;

          this.streetList = [
            {
              name: res.data.districtName,
              id: res.data.districtId
            }
          ];
          this.communityList = [
            {
              name: res.data.communityName,
              id: res.data.communityId
            }
          ];
          this.villageList = [
            {
              name: res.data.villageName,
              id: res.data.villageId
            }
          ];
          this.query.streetName = res.data.districtName;
          this.query.communityName = res.data.communityName;
          this.query.villageName = res.data.villageName;

          // 小区数据
          this.form.actualNum = res.data.actualHousehold;
          this.form.checkInNum = res.data.livedHousehold;
          this.form.partakeNum = res.data.joinHousehold;
          // this.form.garbageNum = res.data.garbageDecrement;
          this.form.awarenessRate = res.data.knowRate;
          this.form.accuracy = res.data.rightRate;

          //  分类占比
          res.data.garbagePercentage = res.data.garbagePercentage
            ? JSON.parse(res.data.garbagePercentage)
            : null;
          this.form.perishable = res.data.garbagePercentage.perishable;
          this.form.recyclable = res.data.garbagePercentage.recyclable;
          this.form.harmful = res.data.garbagePercentage.harmful;
          this.form.other = res.data.garbagePercentage.other;
          // 参与率趋势
          res.data.joinTrend = res.data.joinTrend
            ? JSON.parse(res.data.joinTrend)
            : null;
          this.form.participationRate = res.data.joinTrend["joinTrend"];
          var oProgress = document.querySelectorAll("#progress");
          var oProgress_head = document.querySelectorAll("#progress_head");
          var oSpans = document.querySelectorAll("#span");
          for (var i = 0, len = oSpans.length; i < len; i++) {
            oSpans[i].style.left =
              (parseInt(this.form.participationRate[i]) / 100) *
                (oProgress[i].offsetWidth - 20) +
              "px";
            oProgress_head[i].style.width =
              (parseInt(this.form.participationRate[i]) / 100) *
                (oProgress[i].offsetWidth - 20) +
              "px";
          }
        })
        .catch(err => {});
    },
    initProgress() {
      //js获取节点
      var oProgress = document.querySelectorAll("#progress");
      var oProgress_head = document.querySelectorAll("#progress_head");
      var oSpans = document.querySelectorAll("#span");
      var oPercentage = document.querySelectorAll("#percentage");

      for (let i = 0, len = oSpans.length; i < len; i++) {
        oSpans[i].onmousedown = event => {
          var event = event || window.event;
          var x = event.clientX - oSpans[i].offsetLeft;
          document.onmousemove = () => {
            var event = event || window.event;
            var wX = event.clientX - x;

            if (wX < 0) {
              wX = 0;
            } else if (wX >= oProgress[i].offsetWidth - 20) {
              wX = oProgress[i].offsetWidth - 20;
            }

            oProgress_head[i].style.width = wX + "px";
            oSpans[i].style.left = wX + "px";
            oPercentage[i].innerHTML =
              parseInt((wX / (oProgress[i].offsetWidth - 20)) * 100) + "%";
            return false;
          };
          document.onmouseup = () => {
            this.form.participationRate[i] = oPercentage[i].innerHTML;
            console.log(this.form.participationRate);
            document.onmousemove = null;
          };
        };
      }
    },
    // 选择街道
    changeStreet(currentStreetId) {
      console.log(this.query.streetId, currentStreetId);
      this.query.streetName = this.streetList.find(item => {
        return item.id === currentStreetId;
      }).name;
      this.query.communityName = "";
      this.query.villageName = "";

      this.query.communityId = "";
      this.query.villageId = "";
      this.communityList = [];
      this.villageList = [];
    },
    visibleChangeStreet(bool) {
      if (bool) {
        this.getStreetList();
      }
      console.log(bool);
    },
    // 选择社区
    changeCommunity(currentCommunity) {
      console.log(this.query.communityId, currentCommunity);
      this.query.communityName = this.communityList.find(item => {
        return item.id === currentCommunity;
      }).name;
      this.query.villageName = "";

      this.query.villageId = "";
      this.villageList = [];
    },
    visibleChangeCommunity(bool) {
      if (bool) {
        this.getCommunityList();
      }
      console.log(bool);
    },
    getStreetList() {
      this.$axios
        .get("/village/subdistrict/page", {
          params: {
            parentId: 0
          }
        })
        .then(({ data: res }) => {
          console.log("街道数据", res);
          if (res.code != 0) {
            return;
          }
          this.streetList = res.data.list;
        })
        .catch(() => {});
    },
    changeVillage(currentVillageID) {
      console.log(this.query.villageId, currentVillageID);
      this.query.villageName = this.villageList.find(item => {
        return item.id === currentVillageID;
      }).name;
      console.log(this.query);
    },
    // 选择小区
    visibleChangeVillage(bool) {
      if (bool) {
        this.getVillageList();
      }
      console.log(bool);
    },

    // 获取社区
    getCommunityList() {
      if (!this.query.streetId) {
        return this.$message.warning({
          message: "请先选择街道",
          duration: 1500
        });
      }
      // communityList
      this.$axios
        .get("/village/subdistrict/page", {
          params: {
            parentId: this.query.streetId
          }
        })
        .then(({ data: res }) => {
          console.log("社区数据", res);
          if (res.code != 0) {
            return;
          }
          this.communityList = res.data.list;
        })
        .catch(() => {});
    },
    // 获取小区
    getVillageList() {
      if (!this.query.communityId) {
        return this.$message.warning({
          message: "请先选择社区",
          duration: 1500
        });
      }

      this.$axios
        .get("/village/subdistrict/page", {
          params: {
            parentId: this.query.communityId
          }
        })
        .then(({ data: res }) => {
          console.log("小区数据", res);
          if (res.code != 0) {
            return;
          }
          this.villageList = res.data.list;
        })
        .catch(() => {});
    },
    // 获取 easy-mock 的模拟数据
    // getData() {},
    // 取消
    cancel() {
      this.clearForm();
      this.$router.replace({
        path: "/big-screen-manage"
      });
    },

    saveAdd() {
      var params = {
        districtId: this.query.streetId,
        districtName: this.query.streetName,
        communityId: this.query.communityId,
        communityName: this.query.communityName,
        villageId: this.query.villageId,
        villageName: this.query.villageName,

        actualHousehold: this.form.actualNum,
        livedHousehold: this.form.checkInNum,
        joinHousehold: this.form.partakeNum,
        knowRate: this.form.awarenessRate,
        rightRate: this.form.accuracy,
        // garbageDecrement: this.form.garbageNum,

        garbagePercentageDTO: {
          recyclable: this.form.recyclable,
          harmful: this.form.harmful,
          perishable: this.form.perishable,
          other: this.form.other
        },

        joinTrendDTO: {
          joinTrend: this.form.participationRate
        },

        collectionTrendDTO: {
          recyclableTrend: this.form.recyclables,
          harmfulTrend: this.form.harmfuls,
          perishableTrend: this.form.perishables,
          otherTrend: this.form.others
        },

        recycleSortDTO: {
          plastic: this.form.plastic,
          glass: this.form.glass,
          metal: this.form.metal,
          paper: this.form.paper,
          textile: this.form.spin
        }
      };
      // 新增
      if (!this.$route.query.id) {
        for (var key in params.collectionTrendDTO) {
          var bool = params.collectionTrendDTO[key].some(item => {
            return parseInt(item) > 1200;
          });
          if (bool) {
            return this.$message.warning("垃圾收运量不能超过1200");
          }
        }

        this.$axios
          .post("/screen/screendata", params)
          .then(({ data: res }) => {
            console.log(res);
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            }
            this.$router.replace({
              path: "/big-screen-manage"
            });
          })
          .catch(err => {});
      } else {
        this.$axios
          .put("/screen/screendata", {
            ...params,
            id: this.$route.query.id
          })
          .then(({ data: res }) => {
            console.log(res);
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            }
            this.$router.replace({
              path: "/big-screen-manage"
            });
          })
          .catch(err => {});
      }
    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.$message.success("删除成功");
          this.tableData.splice(index, 1);
        })
        .catch(() => {});
    },

    // 预览
    openNewPage() {
      // window.open("http://vue.bangning.vip/big-screen/");
      // window.open("http://vue.bangning.vip/big-screen/");
    },
    // 编辑操作
    // handleEdit(index, row) {
    //   this.idx = index;
    //   this.form = row;
    //   this.editVisible = true;
    // },
    // 保存编辑
    // saveEdit() {
    //   this.editVisible = false;
    //   this.$message.success(`修改第 ${this.idx + 1} 行成功`);
    //   this.$set(this.tableData, this.idx, this.form);
    // },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      // this.getData();
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      // this.getData();
    }
  }
};
</script>

<style lang="scss" scoped>
.handle-box {
  margin-bottom: 60px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 120px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
#box {
  position: relative;
  width: 300px;
  height: 10px;
  margin-bottom: 20px;
  //  margin:100px auto;
}
#progress {
  position: relative;
  width: 100%;
  height: 10px;
  background: #ccc;
  border-radius: 8px;
}
#progress_head {
  width: 0px;
  height: 100%;
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;
  background: gray;
}
#span {
  position: absolute;
  width: 20px;
  height: 18px;
  background: gray;
  top: -4px;
  left: 0px;
  cursor: pointer;
}
#percentage {
  position: absolute;
  // line-height: 30px;
  text-align: center;
  right: -44px;
  top: -5px;
}
</style>
